﻿using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace Common
{
    public static class HttpTool
    {

        /// <summary>
        /// 发送Http请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="Method"></param>
        /// <param name="BodyType"></param>
        /// <param name="Body"></param>
        /// <param name="Header"></param>
        /// <returns></returns>
        public async static Task<HttpWebResponse> SendHttp(string url,
                                                string Method,
                                                int BodyType,
                                                Dictionary<string, object> Body,
                                                Dictionary<string, string> Header = null)
        {
            HttpWebRequest request = null;
            if (Method.IsNullOrWhiteSpace())
            {
                Method = "get";
            }
            if (Method.ToLower() == "get" && Body != null && Body.Count > 0)
            {
                if (!url.Contains('?'))
                {
                    url += "?";
                }
                else
                {
                    url += "&";
                }
                url += Body.SerializeForm();
            }
            request = WebRequest.Create(url) as HttpWebRequest;
            //处理请求头
            request.Headers.Add("Accept", "text/plain");
            request.Headers.Add("User_Agent", "Quartz");
            if (Header != null && Header.Count > 0)
            {
                foreach (var m in Header)
                {
                    request.Headers.Add(m.Key, m.Value);
                }
            }
            request.Method = Method.ToUpper();//请求方式
            //处理请求内容
            if (BodyType == 1)//FromBody
            {
                request.ContentType = "application/json;charset=UTF-8";
                if (Method.ToLower() != "get" && Body != null && Body.Count > 0)
                {
                    byte[] bdata = Encoding.UTF8.GetBytes(Body.ToJson());
                    request.ContentLength = bdata.Length;
                    Stream streamOut = request.GetRequestStream();
                    streamOut.Write(bdata, 0, bdata.Length);
                    streamOut.Close();
                }
            }
            else if (BodyType == 2)//FromForm
            {
                request.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
                if (Method.ToLower() != "get" && Body != null && Body.Count > 0)
                {
                    byte[] bdata = Encoding.UTF8.GetBytes(Body.SerializeForm());
                    request.ContentLength = bdata.Length;
                    Stream streamOut = request.GetRequestStream();
                    streamOut.Write(bdata, 0, bdata.Length);
                    streamOut.Close();
                }
            } 
            HttpWebResponse response = null;
            try
            {
                response = (await request.GetResponseAsync()) as HttpWebResponse;
            }
            catch (WebException ex)
            {
                response = ex.Response as HttpWebResponse;
                if (response == null)
                {
                    throw ex;
                }
                if (response.StatusCode != HttpStatusCode.Unauthorized)
                {
                    throw ex;
                }
            }
            return response;
        }

    }
}
